package com.hmdp.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.common.Code;
import com.hmdp.common.R;
import com.hmdp.entity.ShopType;
import com.hmdp.exception.BusinessException;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.hmdp.utils.RedisKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 公众号：是叶十三
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ShopTypeMapper shpeTypeMapper;


    @Override
    public R showList() {
        // 1、先去缓存中查询是否存在
        String redisKey = RedisKeyUtils.getShopTypeListKey();
        List<ShopType> shopTypeList = (ArrayList<ShopType>)redisTemplate.opsForValue().get(redisKey);
        // 2、如果缓存中有，直接返回
        if (ObjectUtil.isNotNull(shopTypeList)){
            return R.ok(shopTypeList);
        }
        // 3、如果缓存中没有，去查数据库
        LambdaQueryWrapper<ShopType> lqw = new LambdaQueryWrapper<>();
        // 降序排序
        lqw.orderByAsc(ShopType::getSort);
        shopTypeList = shpeTypeMapper.selectList(lqw);
        if (ObjectUtil.isNull(shopTypeList)){
            throw new BusinessException(Code.BUSINESS_ERR, "店铺类型列表为空");
        }
        // 4、将查询的结果先备份到缓存，再返回
        redisTemplate.opsForValue().set(redisKey,shopTypeList);
        return R.ok(shopTypeList);
    }
}
